package com.coin900.coin.cmd.user;

import com.google.gson.Gson;
import com.coin900.coin.base.FuConstants;
import com.coin900.coin.cmd.ACmd;
import com.coin900.coin.cmd.CmdSign;
import com.coin900.coin.code.CmdCode;
import com.coin900.coin.code.RespCode;
import com.coin900.coin.persist.fu.FuUserAuthVO;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.service.fu.IFuUserAuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shui
 * @create 2017-12-01
 **/
@Controller
public class FuUserAuthPutCmd extends ACmd {
    @Override
    public CmdSign execute(HttpServletRequest request, CmdSign sign) throws Exception {

        CmdSign respSign = new CmdSign(sign);
        FuUserVO user = super.getUser(sign);
        String source = sign.getSource();
        FuUserAuthVO userAuthVO = new Gson().fromJson(source, FuUserAuthVO.class);

        if (StringUtils.isBlank(userAuthVO.getIdCardFacade())) {
            respSign.setMsg("请上传身份证正面照片");
            respSign.setRespCode(RespCode.FAIL);
            return respSign;
        }

        if (StringUtils.isBlank(userAuthVO.getIdCardHandheld())) {
            respSign.setMsg("请上传手持身份证照片");
            respSign.setRespCode(RespCode.FAIL);
            return respSign;
        }

        if (StringUtils.isBlank(userAuthVO.getIdCardReverse())) {
            respSign.setMsg("请上传身份证背面照片");
            respSign.setRespCode(RespCode.FAIL);
            return respSign;
        }

        /**
         * 校验身份证格式是否正确
         */

        Long userId = userAuthVO.getUserId();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        List<FuUserAuthVO> fuUserAuthVOS = this.authService.loadFuUserAuth(params);

        if (fuUserAuthVOS.isEmpty()) {
            // 添加
            userAuthVO.setCreatedInfor(user);
            userAuthVO.setCheckStatus(FuConstants.FU_CHECK_STATUS_ING);
            this.authService.insertFuUserAuth(userAuthVO);
        } else {
            // 修改
            userAuthVO.setModifiedInfor(user);
            userAuthVO.setDataStatus(1);
            this.authService.updateFuUserAuth(userAuthVO);
        }

        return respSign;
    }

    @Autowired
    private IFuUserAuthService authService;

    @Override
    public String getCmdCode() {
        return CmdCode.FU_USER_AUTH_PUT;
    }
}
